#include "udpServer.hpp"
#include "udpUser.hpp"
#include <iostream>
#include <memory>
#include <cstdlib>
#include <cstring>
#include <unordered_map>
#include <string>
#include <fstream>
#include <signal.h>
#include <cstdio>
#include <strings.h>
using namespace Server;
static void Usage(string proc)
{
    cout << "\nusage: \n\t" << proc << " port\n"
         << endl;
}

// -------------------------demo3:聊天室 --------------------
OnlineUser onlineUser;
void routeMessage(int sockfd, string ip, uint16_t port, string message)
{
    if(message == "online") onlineUser.addUser(ip, port);
    if(message == "offonline") onlineUser.delUser(ip, port);

    sockaddr_in client;
    bzero(&client, sizeof client);
    client.sin_family = AF_INET;
    client.sin_addr.s_addr = inet_addr(ip.c_str());
    client.sin_port = htons(port);

    string response;
    if(onlineUser.isOnline(ip, port))
    {
        //如果在线
        response = message;
        onlineUser.broadCast(sockfd, ip, port, response);
    }
    else
    {
        //不在线，单独给不在线的用户发
        response = "you are not online, please input online";
        struct sockaddr_in client;
        memset(&client, 0, sizeof(client));
        client.sin_family = AF_INET;
        client.sin_addr.s_addr = inet_addr(ip.c_str());
        client.sin_port = htons(port);
        sendto(sockfd, response.c_str(), response.size(), 0, (struct sockaddr*)&client, sizeof client);
    }
    
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    unique_ptr<udpServer> usv(new udpServer(routeMessage, port));


    usv->initServer();
    usv->start();
    return 0;
}